package com.salim.leetcode.$38;

public class CountAndSay {
    public String countAndSay(int n) {
        if(n==1){
            return "1";
        }
        return loop("1",1,n);
    }

    private String loop(String prev,int index,int total){
        StringBuilder next = new StringBuilder();
        int duplicate = 1;
        for(int i=0;i<prev.length()-1;i++){
            if(prev.charAt(i) == prev.charAt(i+1)){
                duplicate++;
                continue;
            }else{
                next.append(duplicate).append(prev.charAt(i));
                duplicate = 1;
            }
        }
        next.append(duplicate).append(prev.charAt(prev.length()-1));
        if(++index==total){
            return next.toString();
        }else{
            return loop(next.toString(),index,total);
        }
    }
}
